/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data;

import entities.ArtPhoto;
import entities.User;
import exceptions.FileLoadException;
import exceptions.FileStoreException;
import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import org.apache.commons.fileupload.FileItem;
//import com.sun.media.imageio.plugins.tiff.*;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;

/**
 *
 * @author bertram
 */
public class ImageHandler {

    private static ImageHandler instance;
    private final String imageRoot = "/var/www/billeddeling/images/";
    DataProvider provider = DataProvider.getInstance();

    public ImageHandler() {
    }

    public static ImageHandler getInstance() {
        if (instance == null) {
            instance = new ImageHandler();
        }
        return instance;
    }

    public synchronized ArrayList<ArtPhoto> store(FileItem image, User user) throws FileStoreException {
        String filetype = image.getContentType();
        ArrayList<ArtPhoto> photos = new ArrayList<ArtPhoto>();
        int fileID;
        String suffix = "";
        String fileName = "";
        try {
            fileID = provider.getNextBillede();
            if (image.getContentType().equalsIgnoreCase("image/tiff")) {
                suffix = ".tif";
            } else if (image.getContentType().equalsIgnoreCase("image/jpeg") || image.getContentType().equalsIgnoreCase("image/pjpeg")) {
                suffix = ".jpg";
            } else if (image.getContentType().equalsIgnoreCase("image/png")) {
                suffix = ".png";
            }

            fileName = fileID + suffix;
            ArtPhoto pht = new ArtPhoto();
            pht.setImageID(fileID);
            pht.setPath(fileName);
            pht.setType(filetype);
            int institutionId = user.getInstitution().getId();
            pht.setProvidedBy(provider.getInstitutionByID(institutionId).getName());
            photos.add(pht);
            File uploadedFile = new File(imageRoot + fileName);
            image.write(uploadedFile);

            image.delete();
            if (suffix.equals(".tif")) {
                try {
                    RenderedImage[] imgs = new TiffConverter().readTiff(imageRoot + fileName);
                    fileID = provider.getNextBillede();
                    ImageIO.write(imgs[0], "jpg", new File(imageRoot + fileID + ".jpg"));
                    System.out.println("her: " + imageRoot + fileID + ".jpg");
                    ArtPhoto convertedTifPht = new ArtPhoto();
                    convertedTifPht.setImageID(fileID);
                    convertedTifPht.setType("image/jpeg");
                    convertedTifPht.setPath(fileID + ".jpg");
                    convertedTifPht.setProvidedBy(provider.getInstitutionByID(institutionId).getName());
                    photos.add(0, convertedTifPht);
                   util.Thumbnailer nail= new util.Thumbnailer(imageRoot + fileID+".jpg", imageRoot + "thumbs/" + fileID+".jpg");

                } catch (IOException iex) {
                    System.out.println("hov exception: " + iex.getMessage());
                }

            } else {//vi har ikke konverteret en tiff fil
                util.Thumbnailer nail= new util.Thumbnailer(imageRoot + fileName, imageRoot + "thumbs/" + fileID+".jpg");

            }
        } catch (SQLException ex) {
            System.out.println("sql fejl" + ex.getMessage());
            throw new FileStoreException("kunne ikke gemme billedet fordi jeg er mærkelig");
        } catch (Exception ex) {
            System.out.println("filesystem problem" + ex.getMessage());
            throw new FileStoreException("ups, jeg skrev intet" + ex.getMessage());
        }
        return photos;
    }

    public byte[] getAsBytes(String file) throws FileLoadException {
        FileInputStream instr = null;
        String fileName = imageRoot + file;
        try {
            File fil = new File(fileName);
            System.out.println(fileName);
            instr = new FileInputStream(fil);
            byte[] theBytes = new byte[instr.available()];
            instr.read(theBytes);
            instr.close();
            return theBytes;
        } catch (Exception ex) {
            throw new FileLoadException("jeg loadede intet");
        }
    }
}
